package com.boarsoft.boar.demo.order;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.boarsoft.boar.demo.order.entity.PocOrder;
import com.boarsoft.boar.demo.order.service.PocOrderService;
import com.boarsoft.common.util.StreamUtil;

public class OrderAppTestMain {
	private static final Logger log = LoggerFactory.getLogger(OrderAppTestMain.class);
	private static ClassPathXmlApplicationContext ctx;

	public static void main(String[] args) throws Exception {
		ctx = new ClassPathXmlApplicationContext("classpath:conf/context.xml");
		System.out.println("Startup ".concat(ctx.isRunning() ? "successfully." : "failed."));

		PocOrderService os = ctx.getBean(PocOrderService.class);

		BufferedReader ir = null;
		String cmd = null;
		try {
			System.out.println("Say 'bye' to exit");
			ir = new BufferedReader(new InputStreamReader(System.in));
			while ((cmd = ir.readLine()) != null) {
				// 下单
//				placeOrderTest(os);
				// 查询订单
				// PocOrder o = orderList(os);
				// System.out.println(o);
				// 支付
				finishOrderTest(os, 5564);
				//
				if ("bye".equalsIgnoreCase(cmd)) {
					break;
				}
			}
		} catch (IOException e) {
			log.error("Error on connection", e);
		} finally {
			StreamUtil.close(ir);
		}
		System.out.println("bye");
		System.exit(0);
	}

	// 订单查询
	public static PocOrder orderList(PocOrderService os) {
		PocOrder order = new PocOrder();
		order.setOrderId(3);
		order.setTenantId(12344);
		try {
			return os.find(order.getTenantId(), order.getOrderId());
		} catch (Exception e) {
			log.error("Error on call order.find", e);
		}
		return null;
	}

	// 下单测试
	public static void placeOrderTest(PocOrderService os) {
		// 构建订单数据
		PocOrder order = new PocOrder();
		order.setUserId(666666);
		order.setTenantId(12344);
		order.setProductId(4);
		order.setProductNum(10);
		order.setAmount(10);
		// 下单
		boolean ok = os.place(order);
		System.out.println(ok);
	}

	public static void finishOrderTest(PocOrderService os, int orderId) {
		PocOrder order = new PocOrder();
		order.setOrderId(orderId);
		order.setTenantId(12344);
		boolean ok = os.finish(order, false);
		System.out.println(ok);
	}
}
